.
<template>
  <view class="content">
    <scroll-view scroll-y style="height: calc(100vh - 200rpx)">
      <view class="form" style="padding: 0 40rpx">
        <view class="item">
          <input
            v-model="param.mc"
            maxlength="50"
            placeholder-style="color:#B6BFC6"
            placeholder="请输入任务名称"
          />
          <image
            v-if="param.mc"
            @click="param.mc = ''"
            src="@/static/image/input_delete.png"
          />
        </view>
        <picker
          @change="bindPickerChange"
          :value="role_index"
          :range="role_name"
        >
          <view class="item">
            <input
              v-model="rolename"
              disabled
              placeholder-style="color:#B6BFC6"
              placeholder="请选择角色"
            />
            <image src="@/static/image/arrow_left.png" />
          </view>
        </picker>
        <view v-for="(item, index) in param.jhrwList">
          <view
            style="
              margin-top: 40rpx;
              background: #fafbfa;
              border-radius: 20rpx;
              padding: 20rpx 20rpx 20rpx 20rpx;
            "
          >
            <image
              v-if="param.jhrwList.length > 1"
              class="jian"
              @click="param.jhrwList.splice(index, 1)"
              src="@/static/image/jian.png"
            />
            <view class="item" style="margin-top: 10rpx">
              <input
                style="font-size: 26rpx"
                v-model="item.zz"
                maxlength="50"
                placeholder-style="color:#B6BFC6"
                placeholder="请输入子任务职责"
              />
              <image
                v-if="item.zz"
                @click="clear(index, 'zz')"
                src="@/static/image/input_delete.png"
              />
            </view>
            <!-- <picker @change="bindPickerChange" :value="index" :range="names"> -->
            <view class="item">
              <input
                @click="pickSb(index)"
                style="font-size: 26rpx"
                v-model="item.showText"
                disabled
                placeholder-style="color:#B6BFC6"
                placeholder="请选择设备(非必选)"
              />
              <image
                v-if="item.sbmc"
                style="margin-top: 6rpx"
                @click="clearSb(index)"
                src="@/static/image/input_delete.png"
              />
              <image
                style="width: 32rpx; height: 32rpx; margin: 20rpx 0 0 14rpx"
                v-else
                @click="scan(index)"
                src="@/static/image/scan.png"
              />
            </view>
            <!-- </picker> -->
            <view class="item" style="border-width: 0">
              <input
                @click="chooseLocation(index)"
                style="font-size: 26rpx"
                v-model="item.rwdz"
                disabled
                placeholder-style="color:#B6BFC6"
                placeholder="请选择地址(非必选)"
              />
              <image
                v-if="item.rwdz"
                style="margin-top: 20rpx"
                @click.stop="clear(index, 'rwdz')"
                src="@/static/image/input_delete.png"
              />
            </view>
          </view>
        </view>
        <image
          style="margin-top: 40rpx"
          class="jian"
          @click="add"
          src="@/static/image/jia.png"
        />
      </view>

      <view style="height: 200rpx" />
    </scroll-view>
    <uni-popup ref="popup" type="bottom">
      <view class="search">
        <input
          @input="search"
          v-model="searchValue"
          placeholder-style="color:#B6BFC6"
          placeholder="请输入名称或编码进行搜索"
      /></view>
      <scroll-view
        scroll-y
        style="height: calc(100vh - 360rpx); background: #fff"
      >
        <ly-tree
          v-if="dict.length"
          ref="tree"
          :tree-data="dict"
          :props="props"
          :defaultCheckedKeys="
            param.jhrwList[index].sb_id ? [param.jhrwList[index].sb_id] : []
          "
          node-key="id"
          showRadio
          defaultExpandAll
          :expandOnCheckNode="false"
          checkOnClickNode
          :showNodeIcon="true"
          @check="check"
          :filterNodeMethod="filterNodeMethod"
        >
        </ly-tree>
      </scroll-view>
      <view class="popupwrap">
        <view class="popupbtn" @click="$refs.popup.close()">确定</view>
      </view>
    </uni-popup>
    <view class="popupwrap" style="padding: 60rpx 10vw">
      <view class="popupbtn" style="width: 80vw" @click="submit">添加</view>
    </view>
  </view>
</template>

<script>
import API from "@/common/api.js";
import LyTree from "@/components/ly-tree/ly-tree.vue";
import uniPopup from "@/components/uni-popup/uni-popup.vue";
import QQMapWX from "@/common/qqmap-wx-jssdk.js";
import util from "@/common/util.js";

var x_PI = (3.14159265358979324 * 3000.0) / 180.0;
var PI = 3.1415926535897932384626;
var a = 6378245.0; //卫星椭球坐标投影到平面地图坐标系的投影因子。
var ee = 0.00669342162296594323; //椭球的偏心率。

export default {
  components: {
    LyTree,
    uniPopup,
  },
  data() {
    return {
      qqmap: null,
      user: uni.getStorageSync("user"),
      pzhAuthorization: uni.getStorageSync("pzhAuthorization"),
      role_name: [],
      role_id: [],
      role_index: [],
      rolename: "",
      index: 0,
      param: {
        mc: "",
        role_id: "",
        jhrwList: [
          { zz: "", rwdz: "", sb_id: "", sbmc: "", sn: "", rwjd: "", rwwd: "" },
        ],
      },
      dict: [],
      searchValue: "",

      props: function () {
        return {
          // 这里的label就可以使用函数进行自定义的渲染了
          label(data, node) {
            return node.data.sbmc + `(${node.data.sn})`;
          },
          icon: "ICONURL",
        };
      },
      filterNodeMethod: function (value, data) {
        if (data.sbmc.indexOf(value) > -1 || data.sn.indexOf(value) > -1) {
          return true;
        } else {
          return false;
        }
      },
      index: 0,
      names: [1, 5, 56, 8, 5],
      list: [1, 1, 2],
    };
  },
  onShow() {},
  onLoad(options) {
    this.qqmap = new QQMapWX({
      key: "H43BZ-DKTC4-ZUUU5-XFU3K-JF7U5-EUFV6", // 必填
    });
    this.selectUserRoles();
    this.selectSbTree();
  },
  methods: {
    search() {
      this.$refs.tree.filter(this.searchValue);
    },
    submit() {
      if (this.panduan()) {
        console.log(this.param);
        let data = JSON.parse(JSON.stringify(this.param));
        data.jhrwList.forEach((item, index) => {
          item.xh = index + 1;
          if (!item.sbmc) {
            item.sb_id = 0;
            item.sn = "";
          }
        });
        data.jhrwList = JSON.stringify(data.jhrwList);
        data.pzhAuthorization = this.pzhAuthorization;
        console.log(data);
        API.insertSCCJ(data).then((res) => {
          if (res.resCode == "success") {
            uni.showToast({
              title: "添加成功",
              duration: 2000,
              icon: "success",
              mask: true,
            });
            setTimeout(() => {
              uni.navigateBack({
                delta: 1,
              });
            }, 1500);
          }
        });
      }
    },
    panduan() {
      let msg = "";
      if (!this.param.mc) {
        msg = "请输入任务名称";
      } else if (!this.param.role_id) {
        msg = "请选择角色";
      }
      this.param.jhrwList.forEach((item, index) => {
        if (!msg && !item.zz) {
          msg = "请输入第" + (index + 1) + "个子任务的职责";
        }
      });
      if (msg) {
        uni.showToast({
          title: msg,
          icon: "none",
          duration: 2000,
        });
        return false;
      } else {
        return true;
      }
    },
    chooseLocation(index) {
      uni.chooseLocation({
        success: (r) => {
          this.qqmap.reverseGeocoder({
            location: {
              latitude: r.latitude,
              longitude: r.longitude,
            },
            success: (res) => {
              //成功后的回调
              // let data=util.bd_encrypt(r.longitude,r.latitude)
              let li = this.gcj02_to_wgs84(r.longitude, r.latitude);
              this.param.jhrwList[index].rwjd = li[0];
              this.param.jhrwList[index].rwwd = li[1];

              this.param.jhrwList[index].rwdz =
                res.result.address_component.province +
                res.result.address_component.city +
                res.result.address_component.district +
                (r.address || r.name);
              this.$forceUpdate();
              console.log(li);
            },
            fail: function (error) {
              console.error(error);
            },
            complete: function (res) {
              console.log(res);
            },
          });
        },
      });
    },
    gcj02_to_wgs84(lng, lat) {
      var dlat = this.transformlat(lng - 105.0, lat - 35.0);
      var dlng = this.transformlng(lng - 105.0, lat - 35.0);
      var radlat = (lat / 180.0) * PI;
      var magic = Math.sin(radlat);
      magic = 1 - ee * magic * magic;
      var sqrtmagic = Math.sqrt(magic);
      dlat = (dlat * 180.0) / (((a * (1 - ee)) / (magic * sqrtmagic)) * PI);
      dlng = (dlng * 180.0) / ((a / sqrtmagic) * Math.cos(radlat) * PI);
      let mglat = lat + dlat;
      let mglng = lng + dlng;
      return [lng * 2 - mglng, lat * 2 - mglat];
    },

    //转化经度
    transformlng(lng, lat) {
      var ret =
        300.0 +
        lng +
        2.0 * lat +
        0.1 * lng * lng +
        0.1 * lng * lat +
        0.1 * Math.sqrt(Math.abs(lng));
      ret +=
        ((20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) *
          2.0) /
        3.0;
      ret +=
        ((20.0 * Math.sin(lng * PI) + 40.0 * Math.sin((lng / 3.0) * PI)) *
          2.0) /
        3.0;
      ret +=
        ((150.0 * Math.sin((lng / 12.0) * PI) +
          300.0 * Math.sin((lng / 30.0) * PI)) *
          2.0) /
        3.0;
      return ret;
    },
    transformlat(lng, lat) {
      var ret =
        -100.0 +
        2.0 * lng +
        3.0 * lat +
        0.2 * lat * lat +
        0.1 * lng * lat +
        0.2 * Math.sqrt(Math.abs(lng));
      ret +=
        ((20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) *
          2.0) /
        3.0;
      ret +=
        ((20.0 * Math.sin(lat * PI) + 40.0 * Math.sin((lat / 3.0) * PI)) *
          2.0) /
        3.0;
      ret +=
        ((160.0 * Math.sin((lat / 12.0) * PI) +
          320 * Math.sin((lat * PI) / 30.0)) *
          2.0) /
        3.0;
      return ret;
    },
    check() {
      let list = this.$refs.tree.getCheckedNodes();
      let data = this.param.jhrwList[this.index];
      data.sb_id = "";
      data.sbmc = "";
      list.forEach((item) => {
        data.rwdz = item.sbdz;
        data.rwjd = item.jd;
        data.rwwd = item.wd;
        data.sb_id = item.id;
        data.sbmc = item.sbmc;
        data.sn = item.sn;

        data.showText = item.sbmc + `(${item.sn})`;
      });
      this.param.jhrwList[this.index] = data;
    },
    scan(index) {
      uni.scanCode({
        success: (res) => {
          console.log(res, "www");
          if (res.errMsg == "scanCode:ok") {
            try {
              let data = JSON.parse(res.result);
              if (data.sn) {
                API.selectSbtz({
                  pzhAuthorization: this.pzhAuthorization,
                  flag: "info",
                  canDel: 0,
                  sbbm: data.sn,
                }).then((res) => {
                  if (res.resCode == "success") {
                    uni.hideLoading();
                    if (res.datas.length) {
                      this.param.jhrwList[index] = {
                        zz: this.param.jhrwList[index].zz,
                        sn: res.datas[0].sn,
                        sbmc: res.datas[0].sbmc,
                        sb_id: res.datas[0].id,
                        showText: res.datas[0].sbmc + `(${res.datas[0].sn})`,
                        rwdz: res.datas[0].sbdz,
                        rwjd:
                          res.datas[0].jwdList && res.datas[0].jwdList.length
                            ? res.datas[0].jwdList[0].jd
                            : "",
                        rwwd:
                          res.datas[0].jwdList && res.datas[0].jwdList.length
                            ? res.datas[0].jwdList[0].wd
                            : "",
                      };
                      this.$forceUpdate();
                    } else {
                      uni.showToast({
                        title: "未查询到相关数据",
                        duration: 2000,
                        icon: "none",
                      });
                    }
                  }
                });
              } else {
                uni.showToast({
                  title: "请扫描正确的设备二维码",
                  duration: 2000,
                  icon: "none",
                });
              }
            } catch (err) {
              uni.showToast({
                title: "请扫描正确的设备二维码",
                duration: 2000,
                icon: "none",
              });
            }
          }
        },
      });
    },
    pickSb(index) {
      uni.showLoading();
      this.index = index;
      this.searchValue = "";
      this.$refs.popup.open();
      setTimeout(() => {
        uni.hideLoading();
      }, 3000);
    },
    add() {
      this.param.jhrwList.push({
        zz: "",
        rwdz: "",
        sb_id: "",
        sbmc: "",
        sn: "",
        rwjd: "",
        rwwd: "",
      });
    },
    selectUserRoles() {
      if (uni.getStorageSync("role_id")) {
        this.role_name = uni.getStorageSync("role_name");
        this.role_id = uni.getStorageSync("role_id");
      } else {
        API.selectUserRoles({
          ACCOUNT: this.user.account,
          pzhAuthorization: this.pzhAuthorization,
        }).then((res) => {
          if (res.resCode == "success") {
            uni.hideLoading();
            res.datas.forEach((item) => {
              this.role_name.push(item.NAME);
              this.role_id.push(item.ROLE_ID);
              uni.setStorage({
                key: "role_name",
                data: this.role_name,
              });
              uni.setStorage({
                key: "role_id",
                data: this.role_id,
              });
            });
          }
        });
      }
    },
    toTreeData(data) {
      let resData = data;
      let tree = [];

      for (let i = 0; i < resData.length; i++) {
        if (resData[i].parent_id == "0") {
          resData[i].children = [];
          tree.push(resData[i]);
          resData.splice(i, 1);
          i--;
        }
      }
      run(tree);
      function run(chiArr) {
        if (resData.length !== 0) {
          for (let i = 0; i < chiArr.length; i++) {
            for (let j = 0; j < resData.length; j++) {
              if (chiArr[i].id === resData[j].parent_id) {
                resData[j].children = [];
                chiArr[i].children.push(resData[j]);
                resData.splice(j, 1);
                j--;
              }
            }
            run(chiArr[i].children);
          }
        }
      }
      return tree;
    },
    selectSbTree() {
      if (uni.getStorageSync("sbDict")) {
        this.dict = uni.getStorageSync("sbDict");
      } else {
        API.selectSbTree({
          non_rela: "non_rela",
          pzhAuthorization: this.pzhAuthorization,
        }).then((res) => {
          if (res.resCode == "success") {
            uni.hideLoading();
            this.dict = this.toTreeData(res.datas);
            uni.setStorage({
              key: "sbDict",
              data: this.dict,
            });
          }
        });
      }
    },
    bindPickerChange(e) {
      this.role_index = e.target.value;
      this.param.role_id = this.role_id[this.role_index];
      this.rolename = this.role_name[this.role_index];
    },
    clearSb(index) {
      this.param.jhrwList[index].sb_id = 0;
      this.param.jhrwList[index].sbmc = "";
      this.param.jhrwList[index].sn = "";
      this.param.jhrwList[index].showText = "";
      this.$forceUpdate();
    },
    clear(index, key) {
      this.param.jhrwList[index][key] = "";
      if (key == "rwdz") {
        this.param.jhrwList[index].rwjd = "";
        this.param.jhrwList[index].rwwd = "";
      }
      this.$forceUpdate();
    },
  },
};
</script>
<style lang="less">
.content {
  .uni-popup__wrapper-box {
    padding: 0 !important;
    background: rgba(0, 0, 0, 0) !important;
    max-width: 100% !important;
    margin-top: -220rpx;
  }
}
scroll-view ::-webkit-scrollbar {
  width: 0;
  height: 0;
  color: transparent;
  display: none;
}
</style>
<style lang="less" scoped>
/* #ifndef APP-NVUE */
body {
  font-size: 30rpx;
  line-height: 2em;
  color: #333;
  font-family: Helvetica Neue, Helvetica, sans-serif;
}

view,
text {
  font-size: 30rpx;
  line-height: 2em;
  color: #333;
}

page {
  background: #fff;
}

button {
  width: 100%;
}
/* #endif */
.content {
  height: 100vh;
  background: white;
  .form {
    font-size: 31rpx;
    .jian {
      width: 50rpx;
      height: 50rpx;
      display: block;
      margin-left: calc(100% - 50rpx);
    }
    .item {
      display: flex;
      margin-top: 20rpx;
      border-bottom: 1px solid #eef1f1;
      image {
        width: 40rpx;
        height: 40rpx;
        display: block;
        margin-top: 26rpx;
        transform: rotate(180deg);
      }
      .address {
        width: calc(100% - 104rpx);
        padding-top: 10rpx;
        font-size: 26rpx;
        margin: 0 20rpx;
      }
      input {
        width: calc(100% - 104rpx);
        padding: 20rpx 0;
        font-size: 30rpx;
        margin: 0 20rpx;
      }
      text {
        width: 222rpx;
        font-size: 30rpx;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: rgba(143, 188, 197, 1);
        line-height: 124rpx;
        margin-left: 20rpx;
        text-align: right;
      }
    }
    .Btn {
      margin-top: 100rpx;
      font-size: 30rpx;
      width: 100%;
      line-height: 90rpx;
      color: white;
      background-color: rgb(234, 234, 234);
      border: none;
      outline: none;
      border-radius: 50rpx;
      text-align: center;
    }
  }
  .popupwrap {
    border-top: 2rpx solid rgba(149, 149, 149, 0.1);
    background: white;
    padding: 60rpx 20vw;
    .popupbtn {
      width: 60vw;
      line-height: 80rpx;
      background: #01b7fc;
      color: white;
      text-align: center;
      border-radius: 40rpx;
    }
  }
  .search {
    background: #ffffff;
    padding-top: 20rpx;
    input {
      width: 70vw;
      margin-left: 15vw;
      padding: 0 40rpx;
      box-sizing: border-box;
      border: 1rpx solid #ebedf0;
      border-radius: 40rpx;
      line-height: 60rpx;
      height: 60rpx;
    }
  }
}
</style>
